#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    if (l1 == NULL)
        return l2;
    if (l2 == NULL)
        return l1;
    int count = 0;
    int sum = l1->val + l2->val;
    if (sum >= 10)
    {
        count = 1;
        sum -= 10;
    }
    struct ListNode* phead = malloc(sizeof(struct ListNode));
    phead->next = NULL;
    phead->val = sum;
    struct ListNode* ptail = phead;
    l1 = l1->next;
    l2 = l2->next;
    while (l1 && l2)
    {
        sum = l1->val + l2->val + count;
        count = 0;
        if (sum >= 10)
        {
            count = 1;
            sum -= 10;
        }
        struct ListNode* newnode = malloc(sizeof(struct ListNode));
        newnode->next = NULL;
        newnode->val = sum;
        ptail->next = newnode;
        ptail = newnode;
        l1 = l1->next;
        l2 = l2->next;
    }
    while (l1)
    {
        sum = l1->val + count;
        count = 0;
        if (sum >= 10)
        {
            count = 1;
            sum -= 10;
        }
        struct ListNode* newnode = malloc(sizeof(struct ListNode));
        newnode->next = NULL;
        newnode->val = sum;
        ptail->next = newnode;
        ptail = newnode;
        l1 = l1->next;
    }
    while (l2)
    {
        sum = l2->val + count;
        count = 0;
        if (sum >= 10)
        {
            count = 1;
            sum -= 10;
        }
        struct ListNode* newnode = malloc(sizeof(struct ListNode));
        newnode->next = NULL;
        newnode->val = sum;
        ptail->next = newnode;
        ptail = newnode;
        l2 = l2->next;
    }
    if (count == 1)
    {
        struct ListNode* newnode = malloc(sizeof(struct ListNode));
        newnode->next = NULL;
        newnode->val = count;
        ptail->next = newnode;
    }
    return phead;
}